package bandwidthcontroller;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ppdbuilder
 */
public class TCCommandGenerator implements CommandGenerator{
    
    private final String TC = "sudo tc ";
    private final String ADD_INGRESS = "sudo tc qdisc add dev ";
    private final String DEL_INGRESS = "sudo tc qdisc del dev ";
    private final String ADD_FILTER = "sudo tc filter add dev ";
    private final String ALL_IP_FILTER = " protocol ip u32 match ip src 0.0.0.0/0 police rate ";
    private final Double RATIO = 0.1;
    private String iface;
    private String ingressHandle = "ffff:";
    private BandwidthSettings bw;
    
    TCCommandGenerator(){
        
        
    }
    
    @Override
    public String[] getSetAllBandwidthCommand(BandwidthSettings bw){
        
        
        String rate = bw.getBandwidth();
        this.iface = bw.getIface();
        Double burstval = (Double.parseDouble(rate) * (RATIO));
        double bval = burstval;
        int roundedbval = (int)bval;
        String burst = new Integer(roundedbval).toString()+"kbit";
        rate+="kbit";
        
        StringBuilder command1 = new StringBuilder();
        command1.append(ADD_INGRESS).append(this.iface).append(" handle ").append(this.ingressHandle).append(" ingress");
        Logger.getLogger(TCCommandGenerator.class.getName()).log(Level.INFO, command1.toString());
        String[] commands = new String[2];
        commands[0] = command1.toString();
        
        StringBuilder command2 = new StringBuilder();
        String burstcommand = String.format(" burst %s drop flowid %s",burst,this.ingressHandle);
        command2.append(ADD_FILTER).append(this.iface).append(" parent ").append(this.ingressHandle).append(ALL_IP_FILTER).append(rate).append(burstcommand);
        Logger.getLogger(TCCommandGenerator.class.getName()).log(Level.INFO, command2.toString());
        commands[1] = command2.toString();
        
        return commands;
        
    }
    
    @Override
    public String[] getClearAllBandwidthCommand(BandwidthSettings bw){
        
        this.iface = bw.getIface();
        String[] commands = new String[1];
        StringBuilder command1 = new StringBuilder();
        command1.append(DEL_INGRESS).append(this.iface).append(" handle ").append(this.ingressHandle).append(" ingress");
        Logger.getLogger(TCCommandGenerator.class.getName()).log(Level.INFO, command1.toString());
        commands[0] = command1.toString();
        
        return commands;
        
    }
   
    
}